<script setup>
import { ref, reactive, onMounted, getCurrentInstance, onBeforeMount } from 'vue'
import { validate_password, validate_code, validate_email } from '@/utils/validate'
import { GetCode } from '@/api/common'
import { Register, Login } from '@/api/account'
import sha1 from 'js-sha1'
import { useAppStore } from '@/stores/app'
import { useRouter } from 'vue-router'

const appStore = useAppStore()
const $router = useRouter()
const { proxy } = getCurrentInstance()

// import axios from 'axios'
const validate_password_rule = (rule, value, callback) => {
  let regPassword = validate_password(value)
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (!regPassword) {
    callback(new Error('密码格式不正确'))
  } else {
    callback()
  }
}
const validate_passwords_rule = (rule, value, callback) => {
  let regPassword = validate_password(value)
  let password = form.password
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (!regPassword) {
    callback(new Error('密码格式不正确'))
  } else if (password && password !== value) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}
const validate_code_rule = (rule, value, callback) => {
  let res = validate_code(value)
  // 校验通过激活code
  // submit_button_disabled.value = !res;
  if (value === '') {
    callback(new Error('请输入验证码'))
  } else if (!res) {
    callback(new Error('验证码格式不正确'))
  } else {
    callback()
  }
}

const form = reactive({
  username: 'zzz123456789@163.com',
  password: 'a123456',
  passwords: 'a123456',
  code: ''
})
const form_rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'change' },
    { min: 6, max: 30, message: '长度在6-30个字符', trigger: 'change' }
  ],
  password: [{ validator: validate_password_rule, trigger: 'change' }],
  passwords: [{ validator: validate_passwords_rule, trigger: 'change' }],
  code: [{ validator: validate_code_rule, trigger: 'change' }]
}
const data = reactive({
  tab_menu: [
    { type: 'login', label: '登录' },
    { type: 'register', label: '注册' }
  ]
})
let current_menu = ref(data.tab_menu[0].type)
let formRef = ref(null)

let code_button_disabled = ref(false)
let code_button_loading = ref(false)
let code_button_text = ref('获取验证码')
let code_button_timer = ref(null)

let submit_button_disabled = ref(true)
let submit_button_loading = ref(false)
// 切换按钮
const toggleMenu = (type) => {
  current_menu.value = type
}
// 倒计时
const countdown = (time) => {
  let second = time || 60
  code_button_loading.value = false
  code_button_disabled.value = true
  code_button_text.value = `倒计时${second}秒`
  if (code_button_timer.value) {
    clearInterval(code_button_timer.value)
  }
  code_button_timer.value = setInterval(() => {
    second--
    code_button_text.value = `倒计时${second}秒`
    if (second <= 0) {
      code_button_text.value = '重新获取'
      code_button_disabled.value = false
      clearInterval(code_button_timer.value)
    }
  }, 1000)
}
// 获取验证码
const handleGetCode = async () => {
  const username = form.username
  const password = form.password
  const passwords = form.passwords
  if (!validate_email(username)) {
    proxy.$message({
      message: '用户名不能为空 或 格式不正确'
    })
    return false
  }
  if (!validate_password(password)) {
    proxy.$message({
      message: '密码不能为空 或 格式不正确'
    })
  }
  if (current_menu === 'register' && password !== passwords) {
    proxy.$message({
      message: '两次密码不一致'
    })
    return false
  }
  let requestData = {
    username: form.username,
    module: current_menu.value
  }
  code_button_loading.value = true
  code_button_text.value = '发送中'
  // 获取验证码接口
  try {
    let res = await GetCode(requestData)
    // console.log(res, 'res')
    const data = res
    if (data.resCode == 1024) {
      proxy.$message.error(data.message)
      return false
    }
    // 获取验证码成功，解封提交按钮
    submit_button_disabled.value = false
    proxy.$message({
      message: data.message,
      type: 'success'
    })
    countdown()
  } catch (error) {
    // proxy.$message.error(error)
    // console.log(error, 'GetCode error')
    code_button_loading.value = false
    code_button_text.value = '获取验证码'
  }
}
const reset = () => {
  proxy.$refs.formRef.resetFields()
  current_menu.value = 'login'
  code_button_timer.value && clearInterval(code_button_timer.value)
  code_button_text.value = '获取验证码'
  code_button_disabled.value = false
  submit_button_disabled.value = true
  submit_button_loading.value = false
}
// 登录
const login = async () => {
  let requestData = {
    username: form.username,
    password: sha1(form.password),
    code: form.code
  }
  submit_button_loading.value = true
  try {
    let res = await appStore.login(requestData)
    proxy.$message({
      message: res.message,
      type: 'success'
    })
    if (res.resCode == 0) {
      console.log('go console')
      // 路由跳转
      $router.push({
        path: '/console'
      })
    }
    reset()
  } catch (error) {
    console.log(error)
    submit_button_loading = false
  }
}
const register = async () => {
  let requestData = {
    username: form.username,
    password: sha1(form.password),
    code: form.code
  }
  submit_button_loading.value = true
  try {
    let res = await Register(requestData)
    proxy.$message({
      message: res.message,
      type: 'success'
    })
    reset()
  } catch (error) {
    submit_button_loading = false
  }
}
// 提交表单
const submit = (formRef) => {
  if (!formRef) return
  formRef.validate((valid) => {
    if (valid) {
      // console.log('submit!')
      current_menu.value === 'login' ? login() : register()
    } else {
      console.log('error submit!')
    }
  })
}
onMounted(() => {
  // console.log(import.meta.env.VITE_APP_API, 'import.meta.env')
  // const { ctx } = getCurrentInstance()
  // console.log(instance, ctx, 'instance,ctx')
})
onBeforeMount(() => {
  clearInterval(code_button_timer.value)
})
</script>
<template>
  <div id="login">
    <div class="form-wrap">
      <ul class="menu-tab">
        <li
          :class="{
            current: current_menu == item.type
          }"
          v-for="item in data.tab_menu"
          :key="item.type"
          @click="toggleMenu(item.type)"
        >
          {{ item.label }}
        </li>
      </ul>
      <el-form ref="formRef" :rules="form_rules" :model="form">
        <el-form-item prop="username">
          <label class="form-label">用户名</label>
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item prop="password">
          <label class="form-label">密码</label>
          <el-input type="password" v-model="form.password" />
        </el-form-item>
        <el-form-item prop="passwords" v-if="current_menu === 'register'">
          <label class="form-label">确认密码</label>
          <el-input type="password" v-model="form.passwords" />
        </el-form-item>
        <el-form-item prop="code">
          <label class="form-label">验证码</label>
          <div style="width: 100%; display: flex">
            <el-input style="width: 800px" v-model="form.code" />
            <el-button
              :disabled="code_button_disabled"
              :loading="code_button_loading"
              @click="handleGetCode"
              type="primary"
              class="el-button-block"
              >{{ code_button_text }}</el-button
            >
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            :disabled="submit_button_disabled"
            :loading="submit_button_loading"
            type="danger"
            @click="submit(formRef)"
            class="el-button-block"
            >{{ current_menu == 'login' ? '登录' : '注册' }}</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<style lang="scss" scoped>
#login {
  height: 100vh;
  background: url('@/assets/bg3.gif');
  display: flex;
  align-items: center;
  justify-content: center;
  .form-wrap {
    background: rgba(255, 255, 255, 0.2);
    width: 320px;
    padding: 40px;
    backdrop-filter: blur(5px); /* 仅模糊背景 */
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
    color: rgb(134, 130, 130);
    .menu-tab {
      text-align: center;
      li {
        display: inline-block;
        padding: 10px 24px;
        margin: 0 10px;
        font-size: 14px;
        border-radius: 5px;
        cursor: pointer;
        &.current {
          background-color: rgba(0, 0, 0, 0.1);
        }
      }
    }
    .form-label {
      display: block;
      font-style: 14px;
    }
  }
}
</style>
